<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="head-container">
          <el-input
            v-model="substationSearchParams.substationName"
            placeholder="请输入变电站名称"
            clearable
            size="mini"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
            @change="substationSearch"
          />
        </div>
        <div class="head-container">
          <el-radio-group
            v-model="queryData.substationNum"
            ref="substationRadioRef"
            @change="getList"
          >
            <el-radio
              v-for="item in substationOptions"
              :key="item.num"
              :label="item.num"
              size="large"
            >{{ item.substationName }}
            </el-radio>
          </el-radio-group>
        </div>
      </el-col>
      <!-- 并网点信息 -->
      <el-col :span="20">
        <el-row
          :gutter="15"
          class="mb8"
        >
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handelAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-edit"
              :disabled="single"
              size="mini"
              @click="handelEdit"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-delete"
              :disabled="multiple"
              size="mini"
              @click="handelDel"
            >删除
            </el-button>
          </el-col>
          <!-- inline="true" 控制 el-form-item 横向显示 -->
          <el-form
            :model="queryData"
            ref="queryDataRef"
            :inline="true"
            class="el-form-search"
          >
            <!--并网点名称-->
            <el-form-item
              label="名称"
              prop="connectionPointName"
              class="el-form-search-item"
            >
              <el-input
                clearable
                placeholder="并网点名称"
                v-model.trim="queryData.connectionPointName"
              ></el-input>
            </el-form-item>

            <!--地区-->
            <el-form-item
              label="地区"
              prop="area"
              class="el-form-search-item"
            >
              <treeselect
                v-model="queryData.area"
                :options="areaOptions"
                :normalizer="normalizer"
                placeholder="选择地区"
                style="width: 140px"
              />
            </el-form-item>

            <!--搜索、重置按钮-->
            <el-form-item class="el-form-search-item">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="searchQuery"
              >搜索
              </el-button>
              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="resetSearch"
              >重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 列表数据展示 -->
        <el-table
          :data="connPointList"
          :height="tableHeight"
          v-loading="loading"
          border
          stripe
          @selection-change="handelSelectionChange"
          highlight-current-row
        >
          <el-table-column
            type="selection"
            width="55"
          ></el-table-column>
          <el-table-column
            type="index"
            label="#"
            width="50"
          >
            <template slot-scope="scope">
              {{
              (queryData.pageNum - 1) * queryData.pageSize + scope.$index + 1
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="名称"
            prop="connectionPointName"
            width="150"
            align="center"
          ></el-table-column>
          <el-table-column
            label="变电站"
            prop="substation.substationName"
            width="150"
            align="center"
          ></el-table-column>
          <el-table-column
            label="地区"
            prop="ancestorNames"
            width="200"
            align="center"
          ></el-table-column>
          <el-table-column
            label="位置"
            prop="location"
            width="240"
            align="center"
          ></el-table-column>
          <!-- <el-table-column
            label="客户"
            prop="customer.companyName"
            width="100"
            align="center"
          ></el-table-column> -->
          <el-table-column
            label="联系人"
            prop="contactName"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="联系方式"
            prop="phone"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="容量"
            prop="capacity"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="电压等级"
            prop="voltageLevel"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="电流变比"
            prop="currentRatio"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="经度"
            prop="lon"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="维度"
            prop="lat"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-edit"
                size="mini"
                @click="handelEdit(scope.row)"
              >修改
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                @click="handelDel(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryData.pageNum"
          :limit.sync="queryData.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-dialogDrag
      width="800px"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
      >
        <!-- 第一行 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <!--并网点名称-->
            <el-form-item
              label="名称"
              prop="connectionPointName"
            >
              <el-input
                clearable
                placeholder="并网点名称"
                v-model.trim="formData.connectionPointName"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行、第四行、第五行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--变电站-->
            <el-form-item
              label="变电站"
              prop="substationNum"
            >
              <el-select
                clearable
                filterable
                placeholder="请选择变电站"
                v-model="formData.substationNum"
                class="from-select"
              >
                <el-option
                  v-for="item in substationOptions"
                  :key="item.num"
                  :value="item.num"
                  :label="item.substationName"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 地区 -->
            <el-form-item
              label="地区"
              prop="area"
            >
              <treeselect
                v-model="formData.area"
                :options="areaOptions"
                :normalizer="normalizer"
                placeholder="选择地区"
              />
            </el-form-item>
            <!-- 位置 -->
            <el-form-item
              label="位置"
              prop="location"
            >
              <el-input
                clearable
                placeholder="输入并网点位置"
                type="textarea"
                :rows="2"
                :maxlength="100"
                resize="none"
                show-word-limit
                v-model.trim="formData.location"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="容量"
              prop="capacity"
            >
              <el-input
                clearable
                placeholder="并网点容量"
                v-model.trim="formData.capacity"
              >
                <template slot="append">MW</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="电压等级"
              prop="voltageLevel"
            >
              <el-select
                v-model="formData.voltageLevel"
                placeholder="并网点电压等级"
                class="from-select"
              >
                <el-option
                  v-for="dict in voltageLevelOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictLabel"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="电流变比"
              prop="currentRatio"
            >
              <el-input
                clearable
                placeholder="并网点电流变比"
                v-model.trim="formData.currentRatio"
              >
                <!-- <template slot="append">KW</template> -->
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--联系人-->
            <el-form-item
              label="联系人"
              prop="contactName"
            >
              <el-input
                clearable
                placeholder="联系人名称"
                v-model.trim="formData.contactName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--联系方式-->
            <el-form-item label="联系方式">
              <el-input
                clearable
                placeholder="联系方式"
                v-model.trim="formData.phone"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第六行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--经度-->
            <el-form-item
              label="经度"
              prop="lon"
            >
              <el-input
                clearable
                placeholder="经度"
                v-model.trim="formData.lon"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--维度-->
            <el-form-item
              label="纬度"
              prop="lat"
            >
              <el-input
                clearable
                placeholder="纬度"
                v-model.trim="formData.lat"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitFormData"
        >提交</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listConnectionPoint,
  addConnectionPoint,
  getConnectionPointByNum,
  editConnection,
  delConnectionPoint,
} from "@/api/maintenance/connectionPoint";
import { listCustomer } from "@/api/maintenance/customer";
import { listArea } from "@/api/maintenance/area";
import { listSubstation } from "@/api/maintenance/substation";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ConnectionPoint",
  components: { Treeselect },
  data() {
    return {
      loading: true,

      /**搜索框 */
      queryData: {
        pageNum: 1,
        pageSize: 30,
        connectionPointName: undefined, //并网点名称
        area: undefined, //地区
        customerNum: undefined, //客户
        substationNum: undefined, //所属变电站
        orderBy: "update_time",
        isAsc: "asc",
      },

      /**变电站搜索 */
      substationSearchParams: {},

      /**表格,列表数据展示 */
      // 表格的高度
      tableHeight: "calc(100vh - 200px)",
      // 表格数据列表
      connPointList: [],
      total: 0,
      ids: [],
      single: true,
      multiple: true,

      /**对话框 */
      //标题
      title: "",
      //是否显示
      open: false,
      //表单数据
      formData: {
        lon: 0,
        lat: 0,
      },
      rules: {
        connectionPointName: [
          { required: true, message: "并网点名称不能为空", trigger: "blur" },
        ],
        customerNum: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        substationNum: [
          {
            required: true,
            message: "变电站不能为空",
            trigger: "blur",
          },
        ],
        capacity: [
          { required: true, message: "容量不能为空", trigger: "blur" },
          {
            validator: this.formValidation.validateNumber,
            message: "只能输入整数或小数",
            trigger: "blur",
          },
        ],
        area: [{ required: true, message: "地区不能为空", trigger: "blur" }],
        lon: [
          {
            required: true,
            validator: this.formValidation.validatorLongitude,
            message: "经度范围：-180~180（保留小数点后十五位）",
            trigger: ["change", "blur"],
          },
        ],
        lat: [
          {
            required: true,
            validator: this.formValidation.validatorLatitude,
            message: "纬度范围：-90~90（保留小数点后十五位）",
            trigger: ["change", "blur"],
          },
        ],
      },
      customerOptions: [],
      substationOptions: [],
      areaOptions: [],
      voltageLevelOptions: [],
    };
  },
  created() {
    /**查询客户 */
    listCustomer().then((response) => {
      this.customerOptions = response.rows;
    });
    // 查询地区列表
    listArea().then((response) => {
      this.areaOptions = this.handleTree(
        response.data.filter((item) => item.num !== 1),
        "num"
      );
    });
    // 查询变电站信息
    listSubstation().then((response) => {
      this.substationOptions = response.rows;
      // 设置变电站单选项的默认值，取查询到的数据的第一项；
      // 判断变电站的数量，如果为零就设置过滤的变电站ID为一个不可能的值；
      this.queryData.substationNum = this.substationOptions.length > 0 ?this.substationOptions[0].num:-1;
      // 设置queryData，如果把this.getList();放入到方法外边，设置的参数不生效
      this.getList();
    });
    this.getDicts("zk_voltage_level").then((response) => {
      this.voltageLevelOptions = response.data;
    });
  },

  methods: {
    /**查询列表数据 */
    getList() {
      this.loading = true;

      listConnectionPoint(this.queryData).then((response) => {
        console.log("查询参数：");

        console.log(this.queryData);

        this.connPointList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**重置对对话框form表单 */
    reset() {
      this.formData = {
        substationNum: this.queryData.substationNum,
        lon: 0,
        lat: 0,
      };
      this.resetForm("formDataRef");
      /**查询客户 */
      listCustomer().then((response) => {
        this.customerOptions = response.rows;
      });
      // 查询地区列表
      listArea().then((response) => {
        this.areaOptions = this.handleTree(
          response.data.filter((item) => item.num !== 1),
          "num"
        );
      });
      listSubstation().then((response) => {
        this.substationOptions = response.rows;
      });
    },
    /**新增并网点 */
    handelAdd() {
      this.reset();

      this.title = "新增并网点";
      this.open = true;
    },
    /**修改并网点 */
    handelEdit(row) {
      this.reset();
      this.title = "修改并网点";
      this.open = true;
      const ids = row.num || this.ids[0];
      getConnectionPointByNum(ids).then((response) => {
        this.formData = response.data;
      });
    },
    /**删除并网点 */
    handelDel(row) {
      const ids = row.num || this.ids;
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          delConnectionPoint(ids);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {});
    },
    /**表格多选监听 */
    handelSelectionChange(val) {
      this.ids = val.map((item) => item.num);
      this.single = this.ids.length != 1;
      this.multiple = !this.ids.length;
    },
    /**搜索框 */
    searchQuery() {
      this.getList();
      this.queryData.pageNum = 1;
    },
    /**重置 */
    resetSearch() {
      this.resetForm("queryDataRef");
      this.searchQuery();
    },
    /**提交对话框 */
    submitFormData() {
      this.$refs["formDataRef"].validate((valid) => {
        if (valid) {
          if (this.formData.num != undefined) {
            // 修改
            editConnection(this.formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.open = false;
            });
          } else {
            // 新增
            addConnectionPoint(this.formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.open = false;
            });
          }
        }
      });
    },
    /**取消对话框 */
    close() {
      this.resetForm("formDataRef");
      this.open = false;
    },
    /** 转换地区数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.num,
        label: node.name,
        children: node.children,
      };
    },
    substationSearch() {
      listSubstation(this.substationSearchParams).then((response) => {
        this.substationOptions = response.rows;
      });
    },
  },
};
</script>

<style lang="scss">
.el-radio-group {
  display: flex;
  flex-direction: column;
  .el-radio {
    width: 100%;
    line-height: 35px;
  }
  .is-checked {
    background-color: #f8f8f9;
    font-weight: 600;
  }
}
</style>
